package com.huatai.user.service.impl;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.common.error.exception.ServiceException;
import com.huatai.common.util.AuthUtil;
import com.huatai.user.entity.Department;
import com.huatai.user.mapper.DepartmentMapper;
import com.huatai.user.service.DepartmentService;
import com.huatai.user.vo.DepartmentVo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @program: ht-system
 * @description: 部门管理接口
 * @author: songxiude
 * @create: 2023-02-17 11:51
 **/
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService  {

	/**
	 * 部门保存更新
	 * @param department
	 * @return
	 */
	public boolean saveDepartment(Department department) {
		Long userId = AuthUtil.getUser().getUserId();
		//如果没有传id就是新增部门
		if(Objects.isNull(department.getId()) || department.getId().longValue()<=0){
			department.setId(IdWorker.getId());
			department.setCreateUserid(userId);
		}
		department.setUpdateUserid(userId);
		return saveOrUpdate(department);
	}

	/**
	 * 删除部门如果有子部门要先删除子部门
	 * @param deptId
	 * @return
	 */
	public boolean delDept(Long deptId) {
		//先判断是否包含子部门
		Department department = getOne(Wrappers.<Department>lambdaQuery().eq(Department::getParentId, deptId));
		if (!Objects.isNull(department)) {
			throw new ServiceException("该部门包含子部门请从最子级往上删除");
		}
		return removeById(deptId);
	}

	/**
	 * 递归获取部门
	 * @return
	 */
	public List<DepartmentVo> getDeptList() {
		List<DepartmentVo> deptList = baseMapper.getDeptList(Wrappers.<Department>lambdaQuery()
			.eq(Department::getStatus,0)
			.orderByAsc(Department::getSort));
		//递归返回
		List<DepartmentVo> list = getTrees(0L, deptList);
		return list;
	}

	@Override
	public List<JSONObject> getDepartList() {
		return this.getBaseMapper().getDeptLists();
	}

	/**
	 * 递归获取子级列表
	 *
	 * @param id
	 * @param trees
	 * @return
	 */
	private List<DepartmentVo> getTrees(Long id, List<DepartmentVo> trees) {
		List<DepartmentVo> list = new ArrayList<>();
		for (DepartmentVo tree : trees) {
			if (tree.getParentId().longValue() == id.longValue()) {
				tree.setChildren(getTrees(tree.getId(), trees));
				list.add(tree);
			}
		}
		return list;
	}
}
